import { message } from 'ant-design-vue'
import axios from 'axios'
import localCache from '@/utils/cache'
import router from '@/router'
// import Qs from 'qs'
// import store from '../store'
// import router from '../router'

let BASE_URL = ''
const TIME_OUT = 10000
if (process.env.NODE_ENV === 'development') {
  BASE_URL = ''
} else if (process.env.NODE_ENV === 'production') {
  BASE_URL = ''
} else {
  BASE_URL = 'http://localhost:8080/'
}

export { BASE_URL, TIME_OUT }

// 创建 axios 实例
const Axios = axios.create({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  // transformRequest: [(data) => { return Qs.stringify(data) }],
  headers: {
    'Access-Control-Allow-Origin': '*',
    // application/json;charset=utf-8
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
})
// 携带cookie
Axios.defaults.withCredentials = true

// 请求拦截器
Axios.interceptors.request.use(
  (config) => {
    if (config.method === 'post' || config.method === 'put') {
      config.headers = {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json;charset=utf-8;charset=UTF-8'
      }
      // config.data = Qs.stringify(config.data)
    }
    if (localCache.getCache('token')) {
      config.headers!.Authorization = `Bearer ${localCache.getCache('token')}`
    }

    // 添加token
    return config
  },
  (error) => {
    console.log(111, error)

    return Promise.reject(error)
  }
)

// 响应拦截器
Axios.interceptors.response.use(
  (response) => {
    // const isLogin = localStorage.getItem('isLogin')
    // if (response.data.code === '401') {
    //   if (isLogin) {
    //     localStorage.removeItem('isLogin')
    //     store.commit('SET_ISLOGIN', false)
    //   }
    //   router.push('/login')
    // } else {
    //   store.commit('SET_ISLOGIN', true)
    //   localStorage.setItem('isLogin', '1') // 设置登录状态
    // }
    return response
  },
  (error) => {
    // 响应错误
    console.log(1111, error)

    const { status, msg } = error.response?.data
    if (status === 401) {
      message.error(msg)
      router.push({ path: '/auth' })
    }
    // if (error.response.status === 403) {
    //   // 根据自定义状态码添加判断
    //   return Promise.reject(error.response);
    // }
    return Promise.reject(error)
  }
)

export default Axios
